package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.article.entity.ApArticle;
import com.heima.article.service.IApArticleService;
import com.heima.article.service.ITemplateService;
import com.heima.common.minio.MinIOService;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import freemarker.template.Configuration;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

@Service
public class ITemplateServiceImpl implements ITemplateService {
    @Autowired
    Configuration configuration;

    @Autowired
    MinIOService minIOService;

    @Autowired
    IApArticleService articleService;
    /*
        生成文章静态页
     */
    @Async
    @Override
    public void publishHTML(ApArticle apArticle, String content) {
        try {
            //找到生成静态页面的模板文件
            Template template = configuration.getTemplate("article.ftl");
            //封装数据
            Map<String,Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            //合并模板和数据
            Writer writer = new StringWriter();
            template.process(map,writer);
            ByteArrayInputStream stream = new ByteArrayInputStream(writer.toString().getBytes());
            String url = minIOService.upload(apArticle.getId() + ".html", stream, "text/html");
            apArticle.setStaticUrl(url);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TemplateException e) {
            e.printStackTrace();
        }
    }
}
